let self;
const app = getApp();
const { projectList } = require('../../config/api/index.js')
const { setStorageSync, getStorageSync, removeStorage, clearStorageSync } = require('../../utils/wcache.js')
Page({
  data: {
		isloading: false,
		projectLists: [],
		currPage: 1,
		dTime: 3600,  // 本地存储有效时间3600s
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		self = this;
		wx.showLoading({
			title: '加载中...',
		})
		self.setData({
			isloading: true,
		})
		let deadtime = wx.getStorageSync('ky_porject_deadtime')  // 获取本地存储时间
		if (deadtime) {
			if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {  // 本地存储失效
				self.getProjectList()
				removeStorage('ky_porject')
			} else {
				setTimeout(function () {
					wx.hideLoading()
				}, 1000)
				self.setData({
					projectLists: getStorageSync('ky_porject'),
				})
			}
		} else {
			self.getProjectList()
		}
		
  },
	getProjectList(params){
		const { currPage, projectLists, dTime } = self.data
		return projectList({
			data:{
				...{ category: 1, per_page:100 },
				...params
			},
			success(res) {
				let totalPages = res.data.total_pages
				if (currPage <= totalPages) {
					self.setData({
						currPage: currPage + 1,
						projectLists: [...projectLists, ...res.data.items]
					})
					setTimeout(function () {
						self.getProjectList({ page: currPage + 1 })
					}, 0)
				} else {
					let lists = [{ id: '379', name: '一月考研辅导', items: [] }, { id: '380', name: '五月同等学力', items: [] }];
					projectLists.forEach((item) => {
						if (item.pid == '379' || item.pid == '380'){
							lists.forEach((e) => {
								if (e.id == item.pid){
									e.items.push(item)
								}
							})
						}
					})
					setStorageSync('ky_porject', lists, dTime)  // 保存本地科目列表
					self.setData({
						projectLists: lists
					})
				}
			},
			complete(res) {
				self.setData({
					isloading: false
				})
			}
		})
	},
	navCourse(e) {
		wx.reLaunch({
			url: '/pages/tabbar/schoollist/schoollist?type=project&id=' + e.currentTarget.dataset.id + '&name=' + e.currentTarget.dataset.name,
		})
	},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})